package com.example.shuiyin.config;

import com.example.shuiyin.security.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.IOException;
import java.util.Enumeration;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
@Slf4j
public class RequestAttributesFilter extends OncePerRequestFilter {

    private final JwtTokenProvider tokenProvider;

    public RequestAttributesFilter(JwtTokenProvider tokenProvider) {
        log.info("初始化RequestAttributesFilter");
        this.tokenProvider = tokenProvider;
        log.info("JwtTokenProvider注入成功: {}", (tokenProvider != null ? "OK" : "NULL"));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 添加调试日志
        if (request.getRequestURI().contains("/api/auth/avatar")) {
            log.debug("Avatar upload request content type: {}", request.getContentType());
            log.debug("Is multipart: {}", isMultipartRequest(request));
            
            // 输出所有请求头
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.info("Header: {} = {}", headerName, request.getHeader(headerName));
            }
        }
        
        // 尝试从请求头中获取JWT令牌并解析用户ID
        if (tokenProvider != null) {
            String jwt = getJwtFromRequest(request);
            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
                try {
                    String userId = tokenProvider.getUserIdFromToken(jwt);
                    if (userId != null) {
                        request.setAttribute("userId", Long.parseLong(userId));
                        log.debug("从JWT令牌中解析出用户ID: {}", userId);
                    }
                } catch (Exception e) {
                    log.warn("解析JWT令牌失败: {}", e.getMessage());
                }
            }
        } else {
            log.warn("JWT令牌提供者为null，无法解析令牌");
        }
        
        // 判断是否是multipart请求
        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
            // 使用Spring的StandardMultipartHttpServletRequest而非commons-fileupload
            if (!(request instanceof StandardMultipartHttpServletRequest)) {
                // 设置请求属性以便处理multipart
                request.setAttribute("org.springframework.web.multipart.support.MultipartFilter.APPLIED", Boolean.TRUE);
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    private String getJwtFromRequest(HttpServletRequest request) {
        // 从请求头获取Token
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        // 从URL参数获取Token
        String tokenParam = request.getParameter("token");
        if (StringUtils.hasText(tokenParam)) {
            return tokenParam;
        }
        
        return null;
    }

    /**
     * 检查请求是否是multipart请求
     */
    private boolean isMultipartRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.toLowerCase().contains("multipart/form-data");
    }
} 